﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Management.Automation;



namespace CheckNetIsolation.CheckNetIsolationInit
{
	class UWPAPPS
	{
		internal async Task<List<Item>> getAllUWPAppInfoAsync()  // 同一个 程序集 可以用 internal替代 public 
		{

			List<Item> items = [

				new Item { ID = "1", AppName = "UWP APP总数为 :"  },


				];

			var appNames = getAppsNameAndAPPID()[1];var appIDs= getAppsNameAndAPPID()[0] ; // 获取所有UWP应用的名称
			if (appNames.Count != 0)
			{
				// 把Count设置为 Item ID为1 的APpName 
				items[0].AppName += appNames.Count.ToString();
			}

			foreach (string appName in appNames)
			{
				string appID = appIDs[appNames.IndexOf(appName)]; 
				string? currentAppPath = @"C:\Program Files\WindowsApps";
				items.Add(new Item { ID = appID, AppName = appName, AppPath = currentAppPath, AppIsChecked = false   });


			}
			return items;
		}

		internal string getAppsPath(string displayName)
		{
			// 创建 PowerShell 会话
			using (PowerShell powerShell = PowerShell.Create())
			{
				// 添加 PowerShell 命令
				powerShell.AddCommand("Get-AppxPackage")
						  .AddCommand("Where-Object")
						  .AddArgument("{ $_.Name -like '*" + displayName + "*' }")
						  .AddCommand("Select-Object")
						  .AddArgument("Name")
						  .AddArgument("InstallLocation");

				// 执行命令
				var results = powerShell.Invoke();
				// 处理结果
				var name = results[0].Properties["Name"]?.Value;
				var installLocation = results[0].Properties["InstallLocation"]?.Value;

				string? appPath = installLocation?.ToString();
				return appPath;
			}


		}
		internal List<string> getAppId()
		{
			List<string> result = [];



			return result;
		}
		internal async Task<string?> GetAppsPathAsync(string displayName)
		{
			return await Task.Run(() =>
			{
				using (PowerShell powerShell = PowerShell.Create())
				{
					try
					{
						// 添加 PowerShell 命令
						powerShell.AddScript($@"
                    Get-AppxPackage | 
                    Where-Object {{ $_.Name -like '*{displayName}*' }} |
                    Select-Object -ExpandProperty InstallLocation
                ");

						// 执行命令
						var results = powerShell.Invoke();

						// 检查结果
						if (results.Count > 0)
						{
							return results[0].ToString();
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine($"PowerShell Error: {ex.Message}");
					}

					return null; // 没有找到匹配的应用
				}
			});
		}

		internal List<List<string>> getAppsNameAndAPPID()
		{

			try
			{
				//  适用  C#的注册表格式 
				var regeditPath = @"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Mappings\";
				// 打开注册表键
				RegistryKey baseKey = Registry.CurrentUser.OpenSubKey(regeditPath);
				var result = new List<List<string>>();
				List<string> resultID = [];
				List<string> resultName = []; 
				if (baseKey != null)
				{
					// 获取子项并筛选
					var appsDirectory = baseKey.GetSubKeyNames()
						.Where(keyName =>
						{
							// 获取DisplayName键的值并进行筛选
							var subKey = baseKey.OpenSubKey(keyName);
							if (subKey != null)
							{
								var displayName = subKey.GetValue("DisplayName") as string;
								return (displayName != null);  
							}
							return false;
						})
						.OrderBy(keyName =>
						{
							// 排序，根据DisplayName的值进行排序
							var subKey = baseKey.OpenSubKey(keyName);
							return subKey?.GetValue("DisplayName") as string;
						})
						.ToList();


					foreach (var appDirectory in appsDirectory)
					{
						// string displayName = appDirectory.GetValue("DisplayName", "Unknown").ToString(); // 使用默认值 "Unknown" 防止 GetValue 返回 null
						var subKey = baseKey.OpenSubKey(appDirectory);
						if (subKey != null)
						{
							string? displayName = subKey.GetValue("DisplayName" , "Unknown" ) as string;
							string appId = appDirectory.Split('\\').Last();  // 获取最后一部分
							Console.WriteLine($"App ID: {appId}, Display Name: {displayName}");

							resultName .Add( displayName);
							resultID.Add(appId); 
							
						}


					}
					Console.WriteLine("Count of UWP apps: " + result.Count);
					result.Add(resultID); 
					result.Add(resultName);
					return result;  
				}
				else
				{
					Console.WriteLine("指定的注册表路径不存在。");
					return new List< List<string>>();
				}
			}

			catch (Exception ex)
			{
				// 打印基本信息
				Console.WriteLine("Exception Message: " + ex.Message);

				// 打印堆栈信息
				Console.WriteLine("Stack Trace: " + ex.StackTrace);

				// 如果有内层异常，则递归打印内层异常
				if (ex.InnerException != null)
				{
					Console.WriteLine("Inner Exception Message: " + ex.InnerException.Message);
					Console.WriteLine("Inner Exception Stack Trace: " + ex.InnerException.StackTrace);
				}
				return new List< List<string>>();
			}
		}




	}
}
